package org.ala.tiktools.sharddb.db.spring;

import org.ala.tiktools.sharddb.db.ShardDatasource;
import org.ala.tiktools.sharddb.db.config.ShardDataSourceConfigInfo;
import org.ala.tiktools.sharddb.db.config.ShardDataSourceConfigInfoParser;
import org.ala.tiktools.sharddb.db.provider.ShardDatasourceProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Map;


/**
 * @author ala
 * @date 2024-12-27 12:18
 */
@Configuration
public class ShardDBConfiguration {


    /**
     *  解析到的所有分库信息
     */
    public static Map<String, ShardDataSourceConfigInfo> DBS;


    /**
     *  解析配置项
     */
    @Bean(value="shardDataSourceConfigInfoParser")
    public ShardDataSourceConfigInfoParser shardDataSourceConfigInfoParser(Environment env) {
        ShardDataSourceConfigInfoParser parser = new ShardDataSourceConfigInfoParser();
        parser.parseConfigInfo(env);
        DBS = parser.getMapper();
        return parser;
    }
    /**
     *  数据源提供器
     */
    @Bean(value="shardDatasourceProvider")
    public ShardDatasourceProvider shardDatasourceProvider(ShardDataSourceConfigInfoParser shardDataSourceConfigInfoParser) {
        ShardDatasourceProvider provider = new ShardDatasourceProvider();
        provider.setConfigParser(shardDataSourceConfigInfoParser);
        provider.initProider();
        return provider;
    }
    /**
     *  分片数据源
     */
    @Bean(value="shardDatasource")
    public ShardDatasource shardDatasource(ShardDatasourceProvider provider) {
        ShardDatasource ds = new ShardDatasource();
        ds.setDataSourceLookup(provider);
        ds.setProvider(provider);
        return ds;
    }
}
